'use client'

import { Product, Category } from "@prisma/client"
import { useState } from "react"
import { EditProductDialog } from "./edit-product-dialog"
import { PencilIcon, TrashIcon } from "@heroicons/react/24/outline"
import { deleteProduct } from "@/actions/product"

// 更新类型定义
type SerializedProduct = Omit<Product, 'price' | 'createdAt' | 'updatedAt'> & {
  price: string
  createdAt: string
  updatedAt: string
  category: Category
}

interface ProductItemProps {
  product: SerializedProduct
}

export function ProductItem({ product }: ProductItemProps) {
  const [isEditOpen, setIsEditOpen] = useState(false)

  const handleDelete = async () => {
    if (confirm('确定要删除该商品吗？')) {
      try {
        await deleteProduct(product.id)
      } catch (error) {
        console.error('删除商品失败:', error)
      }
    }
  }

  return (
    <>
      <tr>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm font-medium text-gray-900">{product.name}</div>
          <div className="text-sm text-gray-500">{product.description}</div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm text-gray-900">{product.code}</div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm text-gray-900">{product.category.name}</div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <div className="text-sm text-gray-900">
            ¥{product.price}/{product.unit}
          </div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
            product.stock > 0
              ? 'bg-green-100 text-green-800'
              : 'bg-red-100 text-red-800'
          }`}>
            {product.stock}
          </span>
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
          <button
            onClick={() => setIsEditOpen(true)}
            className="text-indigo-600 hover:text-indigo-900 mr-4"
          >
            <PencilIcon className="h-5 w-5" />
          </button>
          <button
            onClick={handleDelete}
            className="text-red-600 hover:text-red-900"
          >
            <TrashIcon className="h-5 w-5" />
          </button>
        </td>
      </tr>
      <EditProductDialog
        product={product}
        open={isEditOpen}
        onClose={() => setIsEditOpen(false)}
      />
    </>
  )
} 